import math

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import pandas as pd
import xlrd  # 引入模块
# import yaml
from .Seismic import Lbzl, Seismic
from .gain import gain
import copy
import time
from PIL import Image

from utils.index import resource_path


def vspplot(cfg, progress_wrapper):
    #####################################################################
    # READ SEGY
    #####################################################################
    start = time.time()
    progress_wrapper.setValue(0)
    s1 = Seismic.from_segyio(cfg['seisdata'])  # 地面文件，读取
    lb = []
    ssfc = []
    py = []
    font = []
    for ii in range(0, cfg['wellnum']):
        sname = 'welldata' + str(ii + 1)  # welldata1, welldata2, ... 井名
        ssfc.append(cfg['wellfc' + str(ii + 1)])
        if not ssfc[ii] is None:
            df = pd.read_excel(ssfc[ii], sheet_name=0)  # sheet_name指定工作表编号或名称
            df.fillna('', inplace=True)  # 如果为空，则替换为空字符串
            fc = df.iloc[:, 0]
            fctime = df.iloc[:, 1]
            py = df.iloc[:, 2]
            font = df.iloc[:, 3]
        else:
            fc = []
            fctime = []
        s = Seismic.from_segyio(cfg[sname])  # 井数据，读取
        s.data = gain(s.data, s.dt, 'agc', cfg['agc'], 2)
        stkcdp = 0
        maxjuli = 999999999
        for i in range(s1.ntraces):
            juli = math.sqrt((s.wellx[0] * 0.1 - s1.cdpx[i]) ** 2 + (s.welly[0] * 0.1 - s1.cdpy[i]) ** 2)
            if juli < maxjuli:
                maxjuli = juli
                stkcdp = i

        temp = Lbzl(cfg['wellname' + str(ii + 1)], cfg['wellfc' + str(ii + 1)], py, font, fc, fctime,
                    cfg['wellts' + str(ii + 1)], stkcdp,
                    maxjuli, s.ntraces / cfg['tpi'], s,cfg['welllrnum' + str(ii + 1)],cfg['wellstep' + str(ii + 1)])

        lb.append(temp)

        # print(stkcdp, maxjuli)
    lb = sorted(lb, key=lambda lb: lb.ssdao)

    print('************************')
    print("读取数据+加AGC+计算位置完成")
    print("开始绘制")
    print('************************')

    # Plot size parameters.

    # Margins, CSS like: top, right, bottom, left.
    mt, mr, mb, ml = 0.3, 0.5, 0.3, 0.5

    # Determine plot dimensions. Kind of laborious and repetitive (see below).
    tpi = cfg['tpi']
    ips = cfg['ips']

    sw1 = s1.ntraces / (5.0*tpi)

    seismic_width = sw1 + cfg['wellnum'] * lb[0].sw + mr + ml
    seismic_height = ips * (cfg['trange'][1] - cfg['trange'][0])

    w = seismic_width + mr + ml
    h = seismic_height + mb + mt

    seismic_left = ml / w

    seismic_bottom = (mb / h)

    seismic_width_fraction1 = sw1 / w
    seismic_width_fraction2 = lb[0].sw / w
    seismic_height_fraction = seismic_height / h
    # Set the tickformat.
    tickfmt = mtick.FormatStrFormatter('%.0f')

    cfg['fontsize'] = cfg['fontsize'] or 30
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文标签
    plt.rcParams['axes.unicode_minus'] = False
    fig = plt.figure(figsize=(w, h), facecolor='w', dpi=300)
    rect_line = []
    s_width = []
    ax = []
    s_width.append(lb[0].ssdao * 1.0 / (lb[0].stepn*tpi))
    temp2 = [seismic_left, seismic_bottom, s_width[0] / w, seismic_height_fraction]
    rect_line.append(temp2)
    temp3 = fig.add_axes(rect_line[0])
    ax.append(temp3)
    for ii in range(0, cfg['wellnum']):
        if ii == cfg['wellnum'] - 1:
            s_width.append(lb[ii].sw)
            temp = (s1.ntraces - lb[ii].ssdao) / (lb[ii].stepn*tpi)
            s_width.append(temp)
        else:
            s_width.append(lb[ii].sw)
            temp = (lb[ii + 1].ssdao - lb[ii].ssdao) / (lb[ii].stepn*tpi)
            s_width.append(temp)

    for ii in range(1, 2 * cfg['wellnum'] + 1):
        temp2 = [seismic_left + sum(s_width[0:ii]) / w, seismic_bottom, s_width[ii] / w, seismic_height_fraction]
        rect_line.append(temp2)
        temp3 = fig.add_axes(rect_line[ii])
        ax.append(temp3)

    print("Start Plot!!!")
    ax[0] = s1.wiggle_plot2(
        ax=ax[0],
        lw=cfg['lineweight'],
        ts=cfg['trange'][0],
        td=cfg['trange'][1],
        stt=0,
        sein=lb[0].ssdao,
        tstep=lb[0].stepn,
        lbf=0,
        lfcf=0,
        rfcf=1,
        lfc=[],
        lfctime=[],
        rfc=lb[0].ssfcdata[1:],
        rfctime=lb[0].ssfctime[1:],
        fcxc=cfg['fcxc'],
        py=lb[0].py[1:],
        font=lb[0].font[1:],
        fontback=cfg['fontsize'],
    )

    for ii in range(1, cfg['wellnum'] + 1):
        ax[2 * ii - 1] = lb[ii - 1].ss.wiggle_plot2(
            ax=ax[2 * ii - 1],
            lw=cfg['lineweight'],
            ts=cfg['trange'][0],
            td=cfg['trange'][1],
            tstep=1,
            lrnum=10,
            lbf=1,
            lfc=lb[ii - 1].ssfcdata[1:],
            lfctime=lb[ii - 1].ssfctime[1:],
            fcxc=cfg['fcxc'],
            py=lb[ii-1].py[1:],
            font=lb[ii-1].font[1:],
            name=lb[ii-1].ssname,
            fontback=cfg['fontsize'],
        )

        if ii == cfg['wellnum']:
            ax[ii * 2] = s1.wiggle_plot2(
                ax=ax[ii * 2],
                lw=cfg['lineweight'],
                ts=cfg['trange'][0],
                td=cfg['trange'][1],
                stt=lb[ii - 1].ssdao,
                sein=s1.ntraces,
                tstep=lb[ii-1].stepn,
                lrnum=lb[ii-1].lrnum,
                lbf=0,
                lfcf=1,
                rfcf=0,
                lfc=lb[ii - 1].ssfcdata[1:],
                lfctime=lb[ii - 1].ssfctime[1:],
                fcxc=cfg['fcxc'],
                py=lb[ii - 1].py[1:],
                font=lb[ii - 1].font[1:],
                fontback=cfg['fontsize'],
                name=lb[ii - 1].ssname,
            )
        else:
            ax[ii * 2] = s1.wiggle_plot2(
                ax=ax[ii * 2],
                lw=cfg['lineweight'],
                ts=cfg['trange'][0],
                td=cfg['trange'][1],
                stt=lb[ii - 1].ssdao,
                sein=lb[ii].ssdao,
                tstep=lb[ii-1].stepn,
                lrnum=lb[ii-1].lrnum,
                lbf=0,
                lfcf=1,
                rfcf=1,
                lfc=lb[ii - 1].ssfcdata[1:],
                lfctime=lb[ii - 1].ssfctime[1:],
                rfc=lb[ii].ssfcdata[1:],
                rfctime=lb[ii].ssfctime[1:],
                fcxc=cfg['fcxc'],
                py=lb[ii - 1].py[1:],
                font=lb[ii - 1].font[1:],
                fontback=cfg['fontsize'],
                name=lb[ii - 1].ssname,

            )

    print("Plot OK!!!")

    ax[0].yaxis.set_ticks_position('left')
    ax[-1].yaxis.set_ticks_position('right')
    ax[0].xaxis.set_ticks_position('top')
    ax[0].xaxis.set_ticks_position('top')

    for ii in range(1, 2 * cfg['wellnum']):
        ax[ii].set_yticks([])
        ax[ii].xaxis.set_ticks_position('top')

    # ax5.spines['right'].set_visible(False)
    # ax5.spines['left'].set_visible(False)
    # ax5.spines['top'].set_visible(False)
    # ax5.tick_params(which="major", length=0)
    #
    #
    # ax5.set_yticks([])
    #
    # # startindex=cfg['lpsd']+ cfg['kb']-20)-cfg['zhuzidep1']
    #
    # startindex = int((cfg['lpsd'] + cfg['kb'] - 20 - cfg['zhuzidep1']) * scal) + 158
    # del_index = []
    # for col in range(imsize[1]):
    #     if col < startindex and col > 158:
    #         del_index.append(col)
    #
    # im = np.delete(im, del_index, axis=1)
    #
    # zhuzi.imshow(im, aspect='auto')
    # zhuzi.set_xlim(0, imsize[1])
    # zhuzi.set_ylim(0, imsize[0])
    # if cfg['fcx'] == 1:
    #     for ii in range(0, len(dep)):
    #         # xx = dep[ii] * ((imsize[1] - 158) / (max(s1.cdp) + 63 + cfg['kb'])) + 136
    #         xx = (dep[ii] - cfg['zhuzidep1']) * scal + 136
    #         zhuzi.plot([xx, xx],
    #                    [0, imsize[0]], 'r', lw=2.5 * cfg['lineweight'])
    #
    #
    # zhuzi.invert_xaxis()
    # zhuzi.invert_yaxis()
    #
    # # ax4.yaxis.set_ticks_position('right')
    #

    # ax1.set_ylabel('Time(ms)',
    #                fontsize=cfg['fontsize'] - 20)
    # ax1.set_xlabel('Depth(m)',
    #                fontsize=cfg['fontsize'] - 20,
    #                ha='center')
    #
    # y_major_locator = MultipleLocator(cfg['timeskip'])
    # ax1.yaxis.set_major_locator(y_major_locator)
    # # ticks_loc = np.arange(cfg['trange'][0]*1000, cfg['trange'][1] * 1000.0, cfg['timeskip'])
    # # ax1.set_yticks(ticks_loc)
    # # ax.set_yticks(ax.get_yticks().tolist())
    # # ax1.set_yticklabels(ticks_loc, fontsize=cfg['fontsize'] - 20)
    #
    # ticks_loc = np.arange(int(ax1.viewLim.x1), int(ax1.viewLim.x0), cfg['skip3'])
    #
    # if (cfg['lped'] - ticks_loc[-1]) < 200:
    #     ticks_loc[-1] = cfg['lped']
    # else:
    #     np.append(ticks_loc, mcfg['lped'])
    #     # ticks_loc.append(max(s1.cdp))
    #     # ticks_loc = ax.get_xticks().tolist()
    #     # ticks_loc = np.concatenate((ticks_loc, [max(s1.cdp)]))  # 先将p_变成list形式进行拼接，注意输入为一个tuple
    #     ticks_loc = np.append(ticks_loc, cfg['lped'])
    # ax1.set_xticks(ticks_loc)
    # ax1.set_xticklabels(ticks_loc, fontsize=cfg['fontsize'] - 20)
    #
    # ax1.xaxis.set_major_formatter(tickfmt)
    # ax1.yaxis.set_major_formatter(tickfmt)
    # ax1.set_ylim(1000 * cfg['trange'][1] or 1000 * s1.tbasis[-1],
    #              1000 * cfg['trange'][0])
    #
    # ax1.xaxis.set_ticks_position('top')
    # ax1.xaxis.set_label_position('top')
    # ax1.tick_params(axis='x', width=cfg['lineweight'], colors='black')
    #
    # ax2.set_ylim(1000 * cfg['trange'][1] or 1000 * s1.tbasis[-1],
    #              1000 * cfg['trange'][0])
    #
    # ax3.set_ylim(1000 * cfg['trange'][1] or 1000 * s1.tbasis[-1],
    #              1000 * cfg['trange'][0])
    #
    # ax4.set_ylim(1000 * cfg['trange'][1] + cfg['seitimes'] or 1000 * s1.tbasis[-1],
    #              1000 * cfg['trange'][0] + cfg['seitimes'])
    # y_major_locator1 = MultipleLocator(cfg['timeskip'])
    # ax4.yaxis.set_major_locator(y_major_locator1)
    #
    # # ax_cof.axis['bottom'].set_visible(False)
    # # ax_cof.axis['top'].set_visible(True)
    #
    # ticks_loc = np.arange(20, 20 * (cfg['sein'] - 10) + 20, 300)
    #
    # ticks_loc = np.append(ticks_loc, 20 * cfg['sein'] + 20)
    #
    # ax4.set_xticks(ticks_loc)
    # ticklable = s4.inlin[stkcdp:stkcdp + cfg['sein'] - 10:15]
    # ticklable = np.append(ticklable, 'InLine')
    #
    # ax4.set_xticklabels(ticklable, fontsize=cfg['fontsize'] - 20)
    #
    # ax5.set_xlim(0, 20 * cfg['sein'] + 20)
    # ax5.set_xticks(ticks_loc)
    # ticklable = s4.crosslin[stkcdp:stkcdp + cfg['sein'] - 10:15]
    # ticklable = np.append(ticklable, 'CrossLine')
    # ax5.set_xticklabels(ticklable, fontsize=cfg['fontsize'] - 20)
    # zhuzi.axis('off')
    # # ax5.axis('off')
    #
    # # ax5.axis["新建1"] = ax5.new_fixed_axis(loc="top", offset=(0,-50))
    #
    # # ticks_loc = np.arange(1000*cfg['trange'][0]+cfg['times'] , cfg['trange'][1] * 1000.0+cfg['times'] , cfg['timeskip'])
    # # ax4.set_yticks(ticks_loc)
    # #     # ax.set_yticks(ax.get_yticks().tolist())
    # # ax4.set_yticklabels(ticks_loc, fontsize=cfg['fontsize'] - 20)
    #
    # #####################################################################
    # # SAVE FILE
    # #####################################################################

    # outfile = cfg['outfile']
    # # fig.savefig(outfile, bbox_inches='tight', transparent=True)
    # fig.savefig(outfile, bbox_inches='tight', )

    outfile = resource_path("./static/img/provisional.png")
    fig.savefig(outfile, bbox_inches='tight')  # 支持eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff, webp
    image = Image.open(outfile)
    image.save(cfg['outfile'])

    print(time.time() - start, '完成')
    progress_wrapper.setValue(100)
    print('************************')
    print("Down")
    print('************************')
    return

def jointWellDiagram(cfg, progress_wrapper):
    data_copy = copy.deepcopy(cfg)
    data_copy['tpi'] = data_copy['tpi'] * 2.54
    data_copy['ips'] = data_copy['ips'] / 2.54
    start = time.time()
    vspplot(data_copy, progress_wrapper)
    end = time.time()
    print(f'桥图运行时长：{end - start}秒')
    # saveRecord(record, 'success', 'static/json/bridgeDiagram.json')
    return {
        'status': 'success'
    }


# if __name__ == '__main__':
#     file = open('config.yml')
#     # cfg = yaml.load(file, Loader=yaml.FullLoader)
#     cfg = yaml.load(file, Loader=yaml.FullLoader)
#     cfg['tpi'] = cfg['tpi'] * 2.54
#     cfg['ips'] = cfg['ips'] / 2.54
#
#     vspplot(cfg)
